package com.gzhryc.shared_device.oem.h5.mng.controllers.place;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.TreeResult;
import com.gzhryc.common.excel.ExcelTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStoreType;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreTypeService;
import com.gzhryc.shared_device.oem.h5.mng.DataTools;
import org.apache.commons.fileupload.FileItem;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class PlacePhysicalStoreTypeController {

	static Logger log = Logger.getLogger(PlacePhysicalStoreTypeController.class);

	@Route("/place/physical_store/type/list.html")
	public String list(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		return "/place/physical_store/type/list.html";
	}

	@Route(value = "/place/physical_store/type/list.data")
	public ListResult<PlacePhysicalStoreType> listData(HttpServletRequest request, HttpSession session) {
		ListResult<PlacePhysicalStoreType> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
		try {
			List<PlacePhysicalStoreType> typeList = null;
			Long parentId = WebUtils.getLong(request, "parentId");
			if (parentId != null && parentId > 0) {
				typeList = PlacePhysicalStoreTypeService.self().findByParentId(parentId);
			} else {
				typeList = PlacePhysicalStoreTypeService.self().findRoot();
			}
			if (typeList != null && typeList.size() > 0) {
				result.setCode(DtoConstants.SUCCESS, null);
				result.getBody().setData(typeList);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setMsg("输入参数错误，请检查");
		}
		return result;
	}

	@Route(value = "/place/physical_store/type/add.html")
	public String add(HttpServletRequest request) {
		Long parentId = WebUtils.getLong(request, "parentId");
		if (parentId != null) {
			PlacePhysicalStoreType parent = PlacePhysicalStoreTypeService.self().getById(parentId);
			request.setAttribute("parentId", parent.getId());
			request.setAttribute("parentName", parent.getName());
			request.setAttribute("parentCode", parent.getCode());
		}
		return "/place/physical_store/type/edit.html";
	}

	@Route(value = "/place/physical_store/type/add.do", method = "post")
	public AjaxResult doAdd(HttpServletRequest request) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败");
		PlacePhysicalStoreType type = WebUtils.getParameter(request, PlacePhysicalStoreType.class);
		try {
			if (PlacePhysicalStoreTypeService.self().add(type)) {
				result.setCode(DtoConstants.SUCCESS, null);
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		}
		return result;
	}

	@Route(value = "/place/physical_store/type/update.html")
	public String update(HttpServletRequest request) {
		Long id = WebUtils.getLong(request, "id");
		if (id != null) {
			PlacePhysicalStoreType type = PlacePhysicalStoreTypeService.self().getJoinById(id);
			WebUtils.setAttribute(request, type);
		}
		return "/place/physical_store/type/edit.html";
	}

	@Route(value = "/place/physical_store/type/update.do", method = "post")
	public AjaxResult doUpdate(HttpServletRequest request) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败");
		PlacePhysicalStoreType type = WebUtils.getParameter(request, PlacePhysicalStoreType.class);
		try {
			if (PlacePhysicalStoreTypeService.self().updateNotNull(type)) {
				result.setCode(DtoConstants.SUCCESS, null);
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		}
		return result;
	}

	@Route(value = "/place/physical_store/type/del.do")
	public AjaxResult doDelete(HttpServletRequest request) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败");
		Long id = WebUtils.getLong(request, "id");
		if (id != null) {
			try {
				if (PlacePhysicalStoreTypeService.self().deleteById(id)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setMsg(e.getMessage());
			}
		}
		return result;
	}

	@Route(value = "/place/physical_store/type/excel/export.do")
	public void doExportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String[] titles = {"类型名称","类型代码","父类型代码"};
		List<Object[]> data = new ArrayList<>();

		List<PlacePhysicalStoreType> physicalStoreTypeList = PlacePhysicalStoreTypeService.self().findJoinAll();
		if(physicalStoreTypeList != null && physicalStoreTypeList.size() > 0){
			for(PlacePhysicalStoreType physicalStoreType : physicalStoreTypeList) {
				Object[] objects = new Object[3];
				objects[0] = physicalStoreType.getName();
				objects[1] = physicalStoreType.getCode();
				if(StringTools.isNotBlank(physicalStoreType.getParentCode())) {
					objects[2] = physicalStoreType.getParentCode();
				}
				data.add(objects);
			}
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String name = format.format(new Date());
		WebUtils.exportExcel(response, name);
		ExcelTools.export(response.getOutputStream(), "网点类型信息", null, titles, data);
	}

	@Route(value = "/place/physical_store/type/excel/import.do")
	public AjaxResult doUploadExcel(HttpServletRequest request, FileItem file, HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "导入失败，请稍后再试！");
		try {
			Workbook workbook = ExcelTools.readExcelToWorkbook(file.getName(), file.getInputStream());
			List<Map<String, Object>> list = ExcelTools.readExcel(workbook, new String[]{"name","code","parentCode"}, 0, 1);
			if (list != null && list.size() > 0) {
				Map<String,List<PlacePhysicalStoreType>> data = new HashMap<>();
				List<PlacePhysicalStoreType> rootList = new ArrayList<>();
				for (Map<String, Object> map : list) {
					Object name = map.get("name");
					Object code = map.get("code");
					Object parentCode = map.get("parentCode");
					if(name != null && code != null) {
						PlacePhysicalStoreType physicalStoreType = new PlacePhysicalStoreType();
						physicalStoreType.setName(name.toString());
						physicalStoreType.setCode(code.toString());
						physicalStoreType.setPriority(10);
						physicalStoreType.setCreateDate(new Date());

						if(parentCode != null && StringTools.isNotBlank(parentCode.toString())) {
							physicalStoreType.setParentCode(parentCode.toString());
							List<PlacePhysicalStoreType> cc = data.get(physicalStoreType.getParentCode());
							if(cc == null){
								cc = new ArrayList<>();
							}
							cc.add(physicalStoreType);
							data.put(physicalStoreType.getParentCode(),cc);
						}else{
							rootList.add(physicalStoreType);
						}
					}
				}

				for(PlacePhysicalStoreType physicalStoreType : rootList){
					DataTools.checkChildren(physicalStoreType,data);
				}

				if(data.size() > 0){
					log.error("存在未关联的类型，剩余类型：{{0:json}}",data);
				}

				boolean flag = true;
				for(PlacePhysicalStoreType physicalStoreType : rootList){
					flag = flag && PlacePhysicalStoreTypeService.self().save(physicalStoreType);
				}

				if(flag){
					result.setCode(DtoConstants.SUCCESS,null);
				}
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	@Route(value = "/place/physical_store/type/select.data")
	public TreeResult<PlacePhysicalStoreType> selectData(HttpServletRequest request) {
		TreeResult<PlacePhysicalStoreType> result = new TreeResult<>(DtoConstants.SUCCESS);
		List<PlacePhysicalStoreType> typeTree = PlacePhysicalStoreTypeService.self().findTree();
		result.getBody().setData(typeTree);
		return result;
	}
}
